/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package DAO;

import Connect.ConnectionJDBC;
import DatabasePOJO.user;
import java.sql.*;
import java.text.ParseException;
import java.util.*;
import MD5.*;
import java.util.Date;
import java.text.SimpleDateFormat;
/**
 *
 * @author miayeu
 */
public class UserDAO {
  
    public static int tinhTrangHonNhan(String tinhTrangHonNhan){
        if(tinhTrangHonNhan.equals("Đã kết hôn"))
        {
            return 1;
        }
        return 0;
    }
  
    public static boolean dangKy(user kh) throws ParseException{
        boolean kq=false;
        ConnectionJDBC cnn = new ConnectionJDBC();
        
         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date d = sdf.parse(kh.getNgaySinh());


        String sql=String.format("INSERT INTO `zingdeal`.`user` (`TenDangNhap`, `MatKhau`, `DienThoai`, `Email`, `TenThat`, `GioTinh`, `NgaySinh`, `DiaChi`, `TinhTrangHonNhan`, `lock`, `Type`, `SoDuTaiKhoan`) "
                + "VALUES ('%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', %d, %d, %d, %d)",kh.getTenDangNhap(),MD5.maHoa(kh.getMatKhau()),kh.getDienThoai(),kh.getEmail(),kh.getTenThat(),Integer.parseInt(kh.getGioTinh()),sdf.format(d),kh.getDiaChi(),tinhTrangHonNhan(kh.getTinhTrangHonNhan()),0,2,0);

      
        try{
            cnn.Connect();
            int k=cnn.update(sql);
            if(k==1){
               kq=true;
            }
              cnn.Close();
        }catch(Exception ex){
            System.out.print(sql);
        }
        return kq;
    }
  
    public static user dangNhap(String tenDangNhap, String matKhau) {
        user kh = null;
        ConnectionJDBC cnn = new ConnectionJDBC();
        matKhau=MD5.maHoa(matKhau);
        try {
            String sql = String.format("SELECT * FROM user WHERE TENDANGNHAP=BINARY('%s')"
                    + " AND MATKHAU=BINARY('%s')", tenDangNhap, matKhau);
            
            cnn.Connect();
            ResultSet rs = cnn.getTable(sql);
            if (rs.next()) {
                kh = new user();
                kh.setTenDangNhap(rs.getString("TenDangNhap"));
                  kh.setMatKhau(rs.getString("MatKhau"));
                   kh.setDienThoai(rs.getString("DienThoai"));
                   kh.setEmail(rs.getString("Email"));
                   kh.setTenThat(rs.getString("TenThat"));
                   kh.setGioTinh(rs.getString("GioiTinh"));
                   kh.setNgaySinh(rs.getString("NgaySinh"));
                   kh.setDiaChi(rs.getString("DiaChi"));
                   kh.setTinhTrangHonNhan(rs.getString("TinhTrangHonNhan"));
                   kh.setSoDuTaiKhoan(rs.getString("SoDuTaiKhoan"));
                   kh.setType(rs.getString("Type"));
            }
              cnn.Close();
        } catch (SQLException ex) {
            System.out.println(ex.getMessage());
        }
        return kh;
    }
}
